package com.shallowUniverse.process.context;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shallowUniverse.process.annotation.ProcessBegin;
import com.shallowUniverse.process.context.handler.ProcessHandlerService;
import com.shallowUniverse.process.context.interceptor.ProcessInterceptor;
import com.shallowUniverse.process.context.user.ProcessUserService;
import com.shallowUniverse.process.dto.AppointParam;
import com.shallowUniverse.process.dto.TableField;
import com.shallowUniverse.process.entity.Approval;
import com.shallowUniverse.process.entity.ApprovalDetails;
import com.shallowUniverse.process.entity.ProcessDefinition;
import com.shallowUniverse.process.entity.ProcessNodeDefinition;
import com.shallowUniverse.process.exception.*;
import com.shallowUniverse.process.service.ProcessNodeDefinitionService;
import com.shallowUniverse.process.service.ProcessDefinitionService;
import com.shallowUniverse.process.service.ApprovalDetailsService;
import com.shallowUniverse.process.service.ApprovalService;
import com.shallowUniverse.process.utils.AssertUtil;
import com.shallowUniverse.process.utils.Constant;
import com.shallowUniverse.process.utils.ProcessUtil;
import lombok.Data;
import lombok.ToString;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.*;

/**
 * @author gs
 * @date create in 2021/1/17 11:39
 */
@Data
@ToString
public class ProcessEngine {
    private ProcessUserService processUserService;
    private ProcessHandlerService processHandlerService;
    private ProcessDefinitionService processDefinitionService;
    private ProcessNodeDefinitionService processNodeDefinitionService;
    private ApprovalService approvalService;
    private ApprovalDetailsService approvalDetailsService;
    private List<ProcessInterceptor> processInterceptors;

    public ProcessEngine() {
        processInterceptors = new ArrayList<>();
    }

    public void addInterceptor(ProcessInterceptor processInterceptor) {
        this.processInterceptors.add(processInterceptor);
    }

    /**
     * description: 开启流程 <br/>
     * author: gs   <br/>
     * date: 2021/1/17 <br/>
     * params: [] <br/>
     * return: void
     */
    public Object beginProcess(ProceedingJoinPoint joinPoint, ProcessBegin processBegin) throws ProcessNotFoundException, PrimaryKeyNotFoundException, ApprovalNotExistException, ProcessNodeDefinitionErrorException {
        //定义返回值
        Object returnValue = null;
        try {
            //调用方法保存目标表信息
            returnValue = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //调用方法拿到主键和流程号
        Map<Constant, Object> params = analysisProcessEntry(joinPoint);
        //判断是否为空，为空证明没有增加ProcessEntry注解或者流程号为空
        if (ObjectUtils.isEmpty(params)) {
            return returnValue;
        }
        //保存申请单
        int count = approvalService.save(processBegin.value(), params);
        //返回返回值
        return returnValue;
    }

    /**
     * description: 获取主键值 <br/>
     * author: gs   <br/>
     * date: 2020/12/18 <br/>
     * params: [joinPoint] <br/>
     * return: java.lang.Object
     */
    private Map<Constant, Object> analysisProcessEntry(ProceedingJoinPoint joinPoint) throws PrimaryKeyNotFoundException {
        //判断是否返回了result（没有返回就从ProcessEntry中尝试获取）
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //拿到参数
        Map<Constant, Object> params = ProcessUtil.parseProcessEntry(method, joinPoint.getArgs());
        //判断参数是否为空
        if (ObjectUtils.isEmpty(params)) {
            return null;
        }
        //判断流程号是否为空
        if (ObjectUtils.isEmpty(params.get(Constant.PROCESS_FIELD))) {
            return null;
        }
        //判断主键是否为空
        AssertUtil.primaryKeyNotNull(params.get(Constant.PRIMARY_KEY));
        return params;
    }

    /**
     * description: 获取所有流程 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processDefinition] <br/>
     * return: java.util.List<com.qianyu.process.entity.ProcessDefinition> <br/>
     * version: 1.0
     */
    public List<ProcessDefinition> findProcessDefinitions(ProcessDefinition processDefinition) {
        return processDefinitionService.find(processDefinition);
    }

    /**
     * description: 分页查询流程 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [page,processDefinition] <br/>
     * return: com.baomidou.mybatisplus.core.metadata.IPage<com.qianyu.process.entity.ProcessDefinition> <br/>
     * version: 1.0
     */
    public IPage<ProcessDefinition> findProcessDefinitionPage(IPage<ProcessDefinition> page, ProcessDefinition processDefinition) {
        return processDefinitionService.findPage(page, processDefinition);
    }

    /**
     * description: 注册流程 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processDefinition] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int registerProcessDefinition(ProcessDefinition processDefinition) {
        return processDefinitionService.save(processDefinition);
    }

    /**
     * description: 注册流程节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processNodeDefinition] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int registerProcessNodeDefinition(ProcessNodeDefinition processNodeDefinition) {
        return processNodeDefinitionService.save(processNodeDefinition);
    }

    /**
     * description: 批量注册流程节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processNodeDefinitions] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int registerProcessNodeDefinition(List<ProcessNodeDefinition> processNodeDefinitions) {
        return processNodeDefinitionService.saveBatch(processNodeDefinitions);
    }

    /**
     * description: 根据id查找流程 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processId] <br/>
     * return: com.qianyu.process.entity.ProcessDefinition <br/>
     * version: 1.0
     */
    public ProcessDefinition findProcessDefinitionById(Long processId) {
        return processDefinitionService.findById(processId);
    }

    /**
     * description: 根据id查找流程节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/26 <br/>
     * params: [processNodeId] <br/>
     * return: java.util.List<com.qianyu.process.entity.ProcessNodeDefinition> <br/>
     * version: 1.0
     */
    public List<ProcessNodeDefinition> findProcessNodeDefinitionById(Long processNodeId) {
        return processNodeDefinitionService.findByIds(Collections.singletonList(processNodeId));
    }

    /**
     * description: 审批 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approvalDetails] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int approvalExecute(ApprovalDetails approvalDetails) throws ApprovalNotExistException, AuthenticationException {
        return approvalDetailsService.save(approvalDetails);
    }

    /**
     * description: 根据审批单查找详情 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approvalId] <br/>
     * return: java.util.List<com.qianyu.process.entity.ApprovalDetails> <br/>
     * version: 1.0
     */
    public List<ApprovalDetails> findApprovalDetails(ApprovalDetails approvalDetails) {
        return approvalDetailsService.find(approvalDetails);
    }

    /**
     * description: 根据审批单分页查询详情 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [page, approvalDetails] <br/>
     * return: com.baomidou.mybatisplus.core.metadata.IPage<com.qianyu.process.entity.ApprovalDetails> <br/>
     * version: 1.0
     */
    public IPage<ApprovalDetails> findApprovalDetailsPage(IPage<ApprovalDetails> page, ApprovalDetails approvalDetails) {
        return approvalDetailsService.findPage(page, approvalDetails);
    }

    /**
     * description: 提供审批单原始数据 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approvalId] <br/>
     * return: java.util.Map<java.lang.String,java.lang.Object> <br/>
     * version: 1.0
     */
    public Map<String, Object> findTableData(Long approvalId) throws ApprovalNotExistException {
        return approvalService.findTableData(approvalId);
    }

    /**
     * description: 根据登陆角色查找审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approval] <br/>
     * return: java.util.List<com.qianyu.process.entity.Approval> <br/>
     * version: 1.0
     */
    public List<Approval> findApprovalByRole(Approval approval) {
        return approvalService.findByRole(approval);
    }

    /**
     * description: 查询所有审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approval] <br/>
     * return: java.util.List<com.qianyu.process.entity.Approval> <br/>
     * version: 1.0
     */
    public List<Approval> findApprovals(Approval approval) {
        return approvalService.find(approval);
    }

    /**
     * description: 分页查询所有审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [page,approval] <br/>
     * return: com.baomidou.mybatisplus.core.metadata.IPage<com.qianyu.process.entity.Approval> <br/>
     * version: 1.0
     */
    public IPage<Approval> findApprovalPage(IPage<Approval> page, Approval approval) {
        return approvalService.findPage(page, approval);
    }

    /**
     * description: 根据角色分页查询审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [page,approval] <br/>
     * return: com.baomidou.mybatisplus.core.metadata.IPage<com.qianyu.process.entity.Approval> <br/>
     * version: 1.0
     */
    public IPage<Approval> findApprovalPageByRole(IPage<Approval> page, Approval approval) {
        return approvalService.findPageByRole(page, approval);
    }

    /**
     * description: 根据登陆用户查找审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approval] <br/>
     * return: java.util.List<com.qianyu.process.entity.Approval> <br/>
     * version: 1.0
     */
    public List<Approval> findApprovalByUser(Approval approval) {
        return approvalService.findByUser(approval);
    }

    /**
     * description: 根据用户分页查询审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [page，approval] <br/>
     * return: com.baomidou.mybatisplus.core.metadata.IPage<com.qianyu.process.entity.Approval> <br/>
     * version: 1.0
     */
    public IPage<Approval> findApprovalPageByUser(IPage<Approval> page, Approval approval) {
        return approvalService.findPageByUser(page, approval);
    }

    /**
     * description: 提供原始表的字段和描述 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approvalId] <br/>
     * return: java.util.List<com.qianyu.process.dto.TableField> <br/>
     * version: 1.0
     */
    public List<TableField> findTableFields(Long approvalId) throws ApprovalNotExistException {
        return approvalService.findTableFields(approvalId);
    }

    /**
     * description: 根据id查找审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approvalId] <br/>
     * return: com.qianyu.process.entity.Approval <br/>
     * version: 1.0
     */
    public Approval findApprovalById(Long approvalId) {
        return approvalService.findById(approvalId);
    }

    /**
     * description: 根据流程查找节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processNodeDefinition] <br/>
     * return: java.util.List<com.qianyu.process.entity.ProcessNodeDefinition> <br/>
     * version: 1.0
     */
    public List<ProcessNodeDefinition> findProcessNodeDefinitions(ProcessNodeDefinition processNodeDefinition) {
        return this.processNodeDefinitionService.find(processNodeDefinition);
    }

    /**
     * description: 根据id查询节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/28 <br/>
     * params: [ids] <br/>
     * return: java.util.List<com.qianyu.process.entity.ProcessNodeDefinition> <br/>
     * version: 1.0
     */
    public List<ProcessNodeDefinition> findProcessNodeDefinitionByIds(List<Long> ids) {
        return processNodeDefinitionService.findByIds(ids);
    }

    /**
     * description: 根据流程id分页查询节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [page, processNodeDefinition] <br/>
     * return: com.baomidou.mybatisplus.core.metadata.IPage<com.qianyu.process.entity.ProcessNodeDefinition> <br/>
     * version: 1.0
     */
    public IPage<ProcessNodeDefinition> findProcessNodeDefinitionPage(IPage<ProcessNodeDefinition> page, ProcessNodeDefinition processNodeDefinition) {
        return processNodeDefinitionService.findPage(page, processNodeDefinition);
    }

    /**
     * description: 根據id删除流程 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processIds, isLogic] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int removeProcessDefinition(List<Long> processIds, boolean isLogic) throws ProcessNotCompletedException {
        return processDefinitionService.remove(processIds, isLogic);
    }

    /**
     * description: 删除节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processNodeIds, isLogic] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int removeProcessNodeDefinition(List<Long> processNodeIds, boolean isLogic) throws ProcessNotCompletedException {
        return processNodeDefinitionService.remove(processNodeIds, isLogic);
    }

    /**
     * description: 删除审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [approvalIds, isLogic] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int removeApproval(List<Long> approvalIds, boolean isLogic) throws ProcessNotCompletedException {
        return approvalService.remove(approvalIds, isLogic);
    }

    /**
     * description: 删除审批详情 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [ids, isLogic] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int removeApprovalDetails(List<Long> ids, boolean isLogic) {
        return approvalDetailsService.remove(ids, isLogic);
    }

    /**
     * description: 根据流程删除节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processIds, isLogic] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int removeProcessDefinitionByProcess(List<Long> processIds, boolean isLogic) throws ProcessNotCompletedException {
        return processNodeDefinitionService.removeByProcess(processIds, isLogic);
    }

    /**
     * description: 根据审批单逻辑删除审批单 <br/>
     * author: gs   <br/>
     * date: 2021/1/27 <br/>
     * params: [approvalIds, isLogic] <br/>
     * return: int
     */
    public int removeApprovalDetailsByApproval(List<Long> approvalIds, boolean isLogic) {
        return approvalDetailsService.removeByApproval(approvalIds, isLogic);
    }

    /**
     * description: 委派审批单 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [appointParam] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int appoint(AppointParam appointParam) {
        return approvalService.updateApprovePerson(appointParam);
    }

    /**
     * description: 更新流程节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processNodeDefinition] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int updateProcessNodeDefinition(ProcessNodeDefinition processNodeDefinition) {
        return processNodeDefinitionService.update(processNodeDefinition);
    }

    /**
     * description: 批量更新流程节点 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [processNodeDefinitions] <br/>
     * return: int <br/>
     * version: 1.0
     */
    public int updateProcessNodeDefinitionBatch(List<ProcessNodeDefinition> processNodeDefinitions) {
        return processNodeDefinitionService.updateBatch(processNodeDefinitions);
    }

    /**
     * description: 根据id查询审批详情 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/20 <br/>
     * params: [id] <br/>
     * return: com.qianyu.process.entity.ApprovalDetails <br/>
     * version: 1.0
     */
    public ApprovalDetails findApprovalDetailsById(Long id) {
        return approvalDetailsService.findById(id);
    }

    /**
     * description: 注入用户 <br/>
     * author: Shuai Guo   <br/>
     * date: 2021/7/29 <br/>
     * params: [processEngine] <br/>
     * return: void <br/>
     * version: 1.0
     */
    public void autoWriedUser() throws AuthenticationException {
        //执行前置处理器
        if (this.getProcessInterceptors().size() != 0) {
            //拿到当前线程请求
            this.getProcessInterceptors().forEach(processInterceptor -> processInterceptor.beforeExecuteProcessor(((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest()));
        }
        //校验当前用户是否设置完毕
        AssertUtil.notAuthentication(processUserService.get());
    }
}
